package com.qms.qep.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qms.common.core.controller.BaseController;
import com.qms.common.core.domain.AjaxResult;
import com.qms.common.core.page.TableDataInfo;
import com.qms.qep.domain.Nonconforming;
import com.qms.qep.service.INonconformingService;
import com.qms.common.utils.poi.ExcelUtil;
import javax.servlet.http.HttpServletResponse;

/**
 * 不合格品记录Controller
 */
@RestController
@RequestMapping("/qep/nonconforming")
public class NonconformingController extends BaseController {
    @Autowired
    private INonconformingService nonconformingService;

    /**
     * 查询不合格品记录列表
     */
    @PreAuthorize("@ss.hasPermi('qep:nonconforming:list')")
    @GetMapping("/list")
    public TableDataInfo list(Nonconforming nonconforming) {
        startPage();
        List<Nonconforming> list = nonconformingService.selectNonconformingList(nonconforming);
        return getDataTable(list);
    }

    /**
     * 获取不合格品记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('qep:nonconforming:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return success(nonconformingService.selectNonconformingById(id));
    }

    /**
     * 新增不合格品记录
     */
    @PreAuthorize("@ss.hasPermi('qep:nonconforming:add')")
    @PostMapping
    public AjaxResult add(@RequestBody Nonconforming nonconforming) {
        return toAjax(nonconformingService.insertNonconforming(nonconforming));
    }

    /**
     * 修改不合格品记录
     */
    @PreAuthorize("@ss.hasPermi('qep:nonconforming:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody Nonconforming nonconforming) {
        return toAjax(nonconformingService.updateNonconforming(nonconforming));
    }

    /**
     * 删除不合格品记录
     */
    @PreAuthorize("@ss.hasPermi('qep:nonconforming:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(nonconformingService.deleteNonconformingByIds(ids));
    }
    
    /**
     * 导出不合格品记录
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, Nonconforming nonconforming) {
        try {
            // 设置响应头，以便前端能够正确处理响应
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = "不合格品记录数据" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
            
            List<Nonconforming> list = nonconformingService.selectNonconformingList(nonconforming);
            
            // 确保Excel导出时包含关联对象的名称而不仅仅是ID
            for (Nonconforming item : list) {
                // 组合ID和名称，确保导出文件中显示可读性更强的信息
                if (item.getProductId() != null) {
                    item.setProductName(item.getProductName() != null ? 
                        item.getProductId() + "-" + item.getProductName() : String.valueOf(item.getProductId()));
                }
                
                if (item.getBatchId() != null) {
                    item.setBatchCode(item.getBatchCode() != null ? 
                        item.getBatchId() + "-" + item.getBatchCode() : String.valueOf(item.getBatchId()));
                }
                
                if (item.getDefectId() != null) {
                    item.setDefectName(item.getDefectName() != null ? 
                        item.getDefectId() + "-" + item.getDefectName() : String.valueOf(item.getDefectId()));
                }
                
                if (item.getTaskId() != null) {
                    item.setTaskCode(item.getTaskCode() != null ? 
                        item.getTaskId() + "-" + item.getTaskCode() : String.valueOf(item.getTaskId()));
                }
            }
            
            ExcelUtil<Nonconforming> util = new ExcelUtil<>(Nonconforming.class);
            util.exportExcel(response, list, "不合格品记录数据");
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().write("{\"code\":500,\"msg\":\"导出失败：" + e.getMessage() + "\"}");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    /**
     * 统计不合格品数量
     */
    @PreAuthorize("@ss.hasPermi('qep:nonconforming:query')")
    @GetMapping("/count")
    public AjaxResult count(Nonconforming nonconforming) {
        int count = nonconformingService.countNonconforming(nonconforming);
        return success(count);
    }
} 